"""
扩展功能主应用
整合AI分析、任务管理、设备管理、导出等所有功能
"""
from fastapi import FastAPI, HTTPException, Depends
from fastapi.middleware.cors import CORSMiddleware
from fastapi.security import HTTPBearer
from contextlib import asynccontextmanager
import logging
import uvicorn

# 导入原有模块
from .mssql_main import app as original_app
from .api_extended import router as extended_router

# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# 安全认证
security = HTTPBearer()


@asynccontextmanager
async def lifespan(app: FastAPI):
    """应用生命周期管理"""
    # 启动时执行
    logger.info("启动扩展功能服务...")
    
    # 初始化服务
    try:
        # 这里可以添加服务初始化逻辑
        logger.info("服务初始化完成")
    except Exception as e:
        logger.error(f"服务初始化失败: {str(e)}")
        raise
    
    yield
    
    # 关闭时执行
    logger.info("关闭扩展功能服务...")


# 创建扩展应用
app = FastAPI(
    title="4G信号检测系统 - 扩展功能API",
    description="包含AI分析、任务管理、设备管理、数据导出等扩展功能",
    version="2.0.0",
    lifespan=lifespan
)

# 配置CORS
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # 生产环境中应该限制具体域名
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 包含扩展路由
app.include_router(extended_router)

# 包含原有路由（如果需要）
# app.include_router(original_app.router, prefix="/api/v1")


@app.get("/")
async def root():
    """根路径"""
    return {
        "message": "4G信号检测系统 - 扩展功能API",
        "version": "2.0.0",
        "features": [
            "AI信号分析",
            "团队任务管理", 
            "设备管理",
            "数据导出",
            "趋势图和热力图",
            "用户权限管理"
        ]
    }


@app.get("/health")
async def health_check():
    """健康检查"""
    return {
        "status": "healthy",
        "timestamp": "2025-01-27T10:00:00Z",
        "services": {
            "ai_service": "running",
            "task_service": "running", 
            "device_service": "running",
            "export_service": "running",
            "visualization_service": "running"
        }
    }


@app.get("/api/v2/features")
async def get_features():
    """获取功能列表"""
    return {
        "ai_analysis": {
            "description": "AI信号分析功能",
            "endpoints": [
                "POST /api/v2/ai/analyze - 单次AI分析",
                "POST /api/v2/ai/batch-analyze - 批量AI分析"
            ],
            "analysis_types": [
                "signal_quality - 信号质量分析",
                "anomaly_detection - 异常检测", 
                "pattern_recognition - 模式识别"
            ]
        },
        "task_management": {
            "description": "团队任务管理功能",
            "endpoints": [
                "POST /api/v2/tasks - 创建任务",
                "GET /api/v2/tasks - 获取任务列表",
                "PUT /api/v2/tasks/{task_id} - 更新任务",
                "DELETE /api/v2/tasks/{task_id} - 删除任务",
                "GET /api/v2/tasks/board - 任务看板",
                "POST /api/v2/tasks/{task_id}/comments - 添加评论"
            ],
            "task_statuses": ["pending", "in_progress", "completed", "rejected", "cancelled"],
            "priorities": ["low", "medium", "high", "urgent"]
        },
        "device_management": {
            "description": "设备管理功能",
            "endpoints": [
                "POST /api/v2/devices - 注册设备",
                "GET /api/v2/devices - 获取设备列表",
                "PUT /api/v2/devices/{device_id}/status - 更新设备状态",
                "GET /api/v2/devices/{device_id}/statistics - 设备统计",
                "GET /api/v2/devices/alerts - 设备告警"
            ],
            "device_statuses": ["active", "inactive", "maintenance", "error"]
        },
        "data_export": {
            "description": "数据导出功能",
            "endpoints": [
                "POST /api/v2/exports - 导出数据",
                "GET /api/v2/exports - 导出历史",
                "GET /api/v2/exports/{export_id}/download - 下载文件"
            ],
            "export_formats": ["excel", "csv", "json"]
        },
        "visualization": {
            "description": "数据可视化功能",
            "endpoints": [
                "POST /api/v2/visualization/trend - 生成趋势图数据",
                "POST /api/v2/visualization/heatmap - 生成热力图数据"
            ],
            "heatmap_types": ["signal_strength", "frequency", "time_frequency"],
            "color_schemes": ["viridis", "jet", "gray", "hot"]
        }
    }


if __name__ == "__main__":
    uvicorn.run(
        "app.main_extended:app",
        host="0.0.0.0",
        port=8886,
        reload=True,
        log_level="info"
    )